<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(v,k) in scope.row.children"
              :key="v.id"
              :style="{'border-bottom':'1px solid rgb(235, 238, 245)','border-top': k==0 ? '1px solid rgb(235, 238, 245)' : ''}"
            >
              <el-col :span="5">
                <el-tag closable>{{v.authName}}</el-tag>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(vv,kk) in v.children"
                  :key="vv.id"
                  :style="{'border-top':kk!==0?'1px solid rgb(235, 238, 245)':''}"
                >
                  <el-col :span="6">
                    <el-tag closable type="success">{{vv.authName}}</el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="vvv in vv.children"
                      :key="vvv.id"
                      @close="delRight(scope.row,vvv.id)"
                    >{{vvv.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="90"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="240"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="370">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row.id)"
            >删除</el-button>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRightDialog(scope.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        :title="'角色分配权限【'+roleobj.roleName+'】'"
        :visible.sync="rightDialogVisible"
        width="50%"
        @close="rightDialogClosed"
      >
        <el-tree
          :data="rightTreeData"
          show-checkbox
          node-key="id"
          :props="rightTreeProps"
          :default-expand-all="true"
          :default-checked-keys="defaultCheckedKeys"
          ref="rightTreeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="rightRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],

      /** 添加角色1 */
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      /** 添加角色2 */

      /** 修改角色1 */
      editDialogVisible: false,
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      /** 修改角色2 */

      /** 角色分配权限1 */
      roleobj: {},
      rightDialogVisible: false,
      rightTreeData: [],
      rightTreeProps: {
        label: 'authName'
      },
      defaultCheckedKeys: []

      /** 角色分配权限2 */
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    /** 角色分配权限1 */
    getLeafIds(node, keyArr) {
      if (!node.children) {
        return keyArr.push(node.id)
      }
      node.children.forEach(item => this.getLeafIds(item, keyArr))
    },
    async showRightDialog(role) {
      this.rightDialogVisible = true
      const { data: res } = await this.$http.get(`rights/tree`)
      if (res.meta.status !== 200) {
        this.$message.error('获取权限列表数据失败')
      }
      this.rightTreeData = res.data

      this.roleobj = role
      // 获取当前角色拥有的权限ids的集合
      const keys = []
      this.getLeafIds(role, keys)
      this.defaultCheckedKeys = keys
    },
    rightDialogClosed() {
      this.rightDialogVisible = false
      // this.$refs.rightFormRef.resetFields()
    },
    async rightRole() {
      const kFull = this.$refs.rightTreeRef.getCheckedKeys()
      const kHalf = this.$refs.rightTreeRef.getHalfCheckedKeys()
      // console.log(k_full)
      // console.log(k_half)

      const keys = [...kFull, ...kHalf].join(',')

      if (!keys) {
        return this.$message.error('请选取权限')
      }

      const { data: res } = await this.$http.post(
        `roles/${this.roleobj.id}/rights`,
        { rids: keys }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getRoleList()
      this.rightDialogClosed()
      this.$message.success(res.meta.msg)
    },
    /** 角色分配权限2 */

    /** 添加角色1 */
    showAddDialog() {
      this.addDialogVisible = true
    },
    addDialogClosed() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addForm)

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getRoleList()
          this.addDialogClosed()
          this.$message.success(res.meta.msg)
        }
      })
    },
    /** 添加角色2 */

    /** 修改角色1 */
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        this.$message.error('获取修改角色失败')
      }

      this.editForm = res.data
    },
    editDialogClosed() {
      this.editDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    editRole() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `roles/` + this.editForm.roleId,
            this.editForm
          )

          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }

          this.getRoleList()
          this.editDialogClosed()
          this.$message.success(res.meta.msg)
        }
      })
    },
    /** 修改角色2 */

    async delRight(role, rightId) {
      const cfm = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        role.children = res.data
        this.$message.success(res.meta.msg)
      }
    },

    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败！')
      }
      // console.log(res)
      this.roleList = res.data
    },

    async delRole(id) {
      const cfm = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${id}`)

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.getRoleList()
        this.$message.success(res.meta.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
  box-shadow: 0 1px 1px rgb(199, 202, 205);
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
.el-tag {
  margin: 10px 5px;
}
</style>
